package com.yz.forlogin.security.service;

import com.yz.forlogin.security.entity.Admin;
import com.yz.forlogin.security.entity.Customer;
import com.yz.forlogin.security.entity.JwtUser;
import com.yz.forlogin.system.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @author 钰杰
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    public UserDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    /**
     * 继承 UserDetailsService
     * 重写loadUserByUsername方法
     *
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Object userByUserName = userService.findUserByUserName(name);
        if (Admin.class.isInstance(userByUserName) ){
            Admin cast = (Admin) userByUserName;
            return new JwtUser(cast);
        }
        else  {
            Customer cast = (Customer) userByUserName;
            return new JwtUser(cast);
        }
    }

}
